package com.sthz.facepay.interceptor;

import com.alibaba.fastjson.JSONObject;

import com.sthz.facepay.enums.ApiResultEnum;
import com.sthz.facepay.model.result.ApiResult;
import com.sthz.facepay.util.ApiResultUtil;
import com.sthz.facepay.util.JwtUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 自定义token拦截器
 * @author luli
 * @version jdk 1.8
 * @date 2019/7/12 11:05
 */
public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURI().toString();
        System.out.println(url);
        if(url.endsWith("/user")){
            return true;
        }
        response.setCharacterEncoding("utf-8");
        String token = request.getHeader("access_token");
        //token不存在
        if (null != token) {
            //验证token是否正确
            boolean result = JwtUtil.verify(token);
            if (result) {
                return true;
            }
        }
        ApiResult apiResult = ApiResultUtil.getApiResult(ApiResultEnum.AUTH_ERROR);
        responseMessage(response,response.getWriter(),apiResult);
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    /**
     * 返回信息给客户端
     *
     * @param response
     * @param out
     * @param apiResult
     */
    private void responseMessage(HttpServletResponse response, PrintWriter out, ApiResult apiResult) {
        response.setContentType("application/json; charset=utf-8");
        out.print(JSONObject.toJSONString(apiResult));
        out.flush();
        out.close();
    }
}
